<template>
    <z-paging ref="paging">
        <view class="top flex_wrap flex_column row_middle"
            ><u-text
                :text="`提交人:${userInfo.salesmanName}`"
                color="#588BF3"
                size="32rpx"
        /></view>
        <u-gap height="14rpx" bgColor="#F5F5F5" />
        <view class="form">
            <u-form
                labelPosition="left"
                :model="model"
                errorType="toast"
                :rules="rules"
                ref="form"
                :labelStyle="labelStyle"
                labelWidth="160rpx"
            >
                <u-form-item
                    label="创建人"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    required
                    prop="creatorName"
                >
                    <u-input
                        placeholder="请输入创建人"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        maxlength="30"
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.creatorName"
                    />
                </u-form-item>
                <u-form-item
                    label="会议主题"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    required
                    prop="theme"
                >
                    <u-input
                        placeholder="请输入主题(30字以内)"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        maxlength="30"
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.theme"
                    />
                </u-form-item>
                <u-form-item
                    label="讲师"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                >
                    <u-input
                        placeholder="请输入"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.lecturer"
                    />
                </u-form-item>
                <u-form-item
                    label="开始时间"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    required
                    prop="startSubmitTime"
                >
                    <u-datetime-picker
                        ref="datetimePicker"
                        :show="pickerShow"
                        mode="datetime"
                        v-model="model.startTime"
                        @confirm="startTimeChange"
                        @cancel="pickerShow = false"
                    ></u-datetime-picker>

                    <u-text
                        align="right"
                        :iconStyle="iconStyle"
                        @click="pickerShow = true"
                        color="#666"
                        size="28rpx"
                        suffixIcon="arrow-right"
                        :text="
                            model.startSubmitTime
                                ? model.startSubmitTime
                                : '请选择开始时间'
                        "
                    />
                </u-form-item>

                <u-form-item
                    label="结束时间"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    required
                    prop="endSubmitTime"
                    :clearIcon="false"
                >
                    <u-datetime-picker
                        ref="datetimePicker2"
                        :show="pickerShow2"
                        mode="datetime"
                        v-model="model.endTime"
                        @confirm="endTimeChange"
                        @cancel="pickerShow2 = false"
                    ></u-datetime-picker>
                    <u-text
                        align="right"
                        :iconStyle="iconStyle"
                        color="#666"
                        size="28rpx"
                        suffixIcon="arrow-right"
                        @click="pickerShow2 = true"
                        :text="
                            model.endSubmitTime
                                ? model.endSubmitTime
                                : '请选择结束时间'
                        "
                    />
                </u-form-item>

                <u-form-item
                    label="地址"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    required
                    prop="illegalPlace"
                >
                    <view style="width: 530rpx">
                        <u--text
                            align="right"
                            :lines="3"
                            :iconStyle="iconStyle"
                            color="#666"
                            size="28rpx"
                            suffixIcon="arrow-right"
                            :text="
                                model.illegalPlace
                                    ? model.illegalPlace
                                    : '请选择地址'
                            "
                            @click="getLocation"
                        />
                    </view>
                </u-form-item>
                <u-form-item
                    label="详细场地"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="address"
                >
                    <u-input
                        placeholder="请输入详细场地"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.address"
                    />
                </u-form-item>
                <u-form-item
                    label="业务归属"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                >
                    <u-input
                        placeholder="请输入"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.businessAffiliation"
                    />
                </u-form-item>
                <u-form-item
                    label="工作人员"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="serviceStaffIdList"
                >
                    <view style="width: 530rpx">
                        <u--text
                            align="right"
                            :lines="3"
                            :iconStyle="iconStyle"
                            color="#666"
                            size="28rpx"
                            suffixIcon="arrow-right"
                            :text="
                                meetingPersonList.length
                                    ? `${meetingPersonList.length}个工作人员`
                                    : '请添加工作人员'
                            "
                            @click="getLocation1"
                        />
                    </view>
                </u-form-item>
                <u-form-item
                    label="主办方"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                >
                    <u-input
                        placeholder="请输入"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.organizer"
                    />
                </u-form-item>
                <u-form-item
                    label="负责人"
                    required
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="organizerPerson"
                >
                    <u-input
                        placeholder="请输入"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.organizerPerson"
                    />
                </u-form-item>
                <u-form-item
                    label="负责人电话"
                    required
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="organizerPhone"
                >
                    <u-input
                        placeholder="请输入"
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.organizerPhone"
                    />
                </u-form-item>
                <u-form-item
                    label="签到限制"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="verifyType"
                >
                    <u-radio-group v-model="model.verifyType" placement="row">
                        <u-radio
                            name="0"
                            label="不限制"
                            :customStyle="{ marginRight: '8px' }"
                        ></u-radio>
                        <u-radio name="1" label="定位限制"></u-radio>
                    </u-radio-group>
                </u-form-item>
                <u-form-item
                    label="会议图片"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    labelPosition="top"
                >
                    <view style="margin-top: 20rpx">
                        <u-upload
                            :maxCount="1"
                            :fileList="fileList1"
                            @delete="deleteVideo"
                            @afterRead="afterRead1"
                            width="196rpx"
                            height="196rpx"
                            compressed
                            maxDuration="30"
                        ></u-upload>
                    </view>
                </u-form-item>
            </u-form>
        </view>
        <view class="bottomFrom"
            ><u-button
                text="提交审核"
                shape="circle"
                :hairline="false"
                :loading="loading"
                :customStyle="buttonCustomStyle"
                @click="submit"
        /></view>
    </z-paging>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import {
    getMeetDetailByMeetId,
    createMeet,
    updateMeet,
} from "@/api/salesmanMeeting.js";
import { mapGetters } from "vuex";
import moment from "moment";
import Person from "./person.vue";
const dayStart = moment(
    new Date(new Date(new Date().toLocaleDateString()).getTime())
);
const dataEnd = moment(
    new Date(
        new Date(new Date().toLocaleDateString()).getTime() +
            24 * 60 * 60 * 1000 -
            1
    )
);
export default {
    computed: {
        ...mapGetters(["userInfo"]),
    },
    data() {
        return {
            pickerShow: false,
            pickerShow2: false,
            loading: false,
            startPicker: "",
            confirmButtonCustomstyle: {
                border: "none",
                height: "52rpx",
            },
            buttonCustomStyle: {
                color: "#FFF",
                backgroundColor: "#588BF3",
                // marginTop: '80rpx'
            },
            indexSearchKeyword: "",
            indexedChoosed: {},
            indexListHeight: 0,
            searchHeight: uni.upx2px(84),
            labelStyle: {
                fontSize: "28rpx",
                color: "#333",
                fontWeight: "bold",
            },
            formItemCustomStyle: {
                padding: "32rpx 0",
            },
            formItemCustomStyle2: {
                padding: "0",
            },
            customInputStyle: {
                backgroundColor: "#F3F3F3",
                height: "80rpx",
                borderRadius: "20rpx",
            },
            iconStyle: "fontSize:28rpx",
            model: {
                theme: "", //主题
                creatorName: "", //主题
                lecturer: "", //主题
                startTime: dayStart,
                endTime: dataEnd,
                startSubmitTime: "", //开始时间
                endSubmitTime: "", //结束时间
                illegalPlace: "", //地址
                address: "", //详细地址
                businessAffiliation: "", //业务归属
                organizer: "", //业务归属
                organizerPerson: "", //业务归属
                organizerPhone: "", //业务归属
                serviceStaffIdList: [], //业务归属
                coordinatesX: "", //经度
                coordinatesY: "", //纬度
                province: "",
                city: "",
                county: "",
                appointType: 0,
                chooseList: [],
                addressName: "",
                verifyType: "0",
            },
            preChooseList: [],
            rules: {
                theme: [{ required: true, message: "请填写会议主题" }],
                creatorName: [{ required: true, message: "请填写创建人" }],
                startSubmitTime: [
                    { required: true, message: "请选择会议开始时间" },
                ],
                endSubmitTime: [
                    { required: true, message: "请选择会议结束时间" },
                ],
                illegalPlace: [{ required: true, message: "请选择地址" }],
                organizerPerson: [
                    { required: true, message: "请选择主办方负责人" },
                ],
                organizerPhone: [
                    { required: true, message: "请选择主办方负责人电话" },
                ],
            },
            fileList1: [],
            personList: [],
            meetingPersonList: [],
            checkState0meetId: "",
        };
    },
    onReady() {
        this.$refs.form.setRules(this.rules);
        // 微信小程序需要用此写法
        this.$refs.datetimePicker.setFormatter(this.formatter);
        this.$refs.datetimePicker2.setFormatter(this.formatter);
    },
    onShow() {
        this.meetingPersonList = uni.getStorageSync("meetingPersonList") || [];
    },
    onLoad(options) {
        // this.loading = true;
        this.checkState0meetId = options?.meetId ?? "";
        this.checkState0meetId &&
            uni.$u.sleep(400).then(() => {
                this.getMeetDetail(this.checkState0meetId);
                uni.setNavigationBarTitle({
                    title: "编辑会议",
                });
            });
    },
    onUnload() {
        // 移除监听事件
        uni.setStorageSync("meetingPersonList", []);
    },
    created() {
        this.startPicker = Date.now();
        this.model.creatorName = this.userInfo.salesmanName;
    },
    mounted() {
        this.showIndexedList = false;
    },
    methods: {
        getMeetDetail(meetId) {
            getMeetDetailByMeetId(meetId)
                .then((res) => {
                    res.data.verifyType = res.data?.verifyType ?? "0";
                    this.model = res.data;
                    this.model.illegalPlace = res.data.addressName;
                    this.fileList1 = [{ url: res.data.picture }];
                    this.model.startSubmitTime = res.data.startTime;
                    this.model.endSubmitTime = res.data.endTime;
                    const serviceStaffList = res.data?.serviceStaffList ?? [];
                    console.log(
                        "object :>> ",
                        serviceStaffList.map((v) => v.id)
                    );
                    this.meetingPersonList = serviceStaffList.map((v) => v.id);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        formatter(type, value) {
            if (type === "year") {
                return `${value}年`;
            }
            if (type === "month") {
                return `${value}月`;
            }
            if (type === "day") {
                return `${value}日`;
            }
            return value;
        },

        async afterRead1(event) {
            this.uploadLoading = true;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList1.length;
            lists.map((item) => {
                this.fileList1.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                this.uploadLoading = false;
                let item = this.fileList1[fileListLen];
                this.fileList1.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deleteVideo(event) {
            this.fileList1.splice(event.index, 1);
        },
        async uploadFilePromise(url) {
            const that = this;
            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },

        submit() {
            this.loading = true;
            const that = this;
            this.$refs.form
                .validate()
                .then((res) => {
                    // uni.$u.toast('校验通过');
                    const params = {
                        coordinatesX: that.model.coordinatesX, //经度
                        coordinatesY: that.model.coordinatesY, //纬度
                        province: that.model.province, //省
                        city: that.model.city, //市
                        county: that.model.county, //区
                        address: that.model.address, //会议详细地址：几层楼门牌号等
                        businessAffiliation: that.model.businessAffiliation, //人员类型
                        organizer: that.model.organizer, //人员类型
                        organizerPerson: that.model.organizerPerson, //人员类型
                        organizerPhone: that.model.organizerPhone, //人员类型
                        appointType: that.model.appointType, //人员类型
                        startTime: that.model.startSubmitTime, //会议开始时间
                        endTime: that.model.endSubmitTime, //会议结束时间
                        addressName: that.model.addressName, //地址名称用于回显地图的名字
                        theme: that.model.theme, //会议主题
                        creatorName: that.model.creatorName, //会议主题
                        lecturer: that.model.lecturer, //会议主题
                        verifyType: that.model.verifyType, //会议主题
                        submitManId: that.userInfo.id,
                        submitManName: that.userInfo.salesmanName,
                        submitManPhone: that.userInfo.mobile,
                        serviceStaffIdList: that.meetingPersonList,
                        picture: this.fileList1.length
                            ? this.fileList1[0]["url"]
                            : "", //会议图片地址
                    };
                    if (Number(that.model.appointType) === 2) {
                        if (that.model.chooseList.length <= 0) {
                            uni.$u.toast("您还没有指定下级");
                            return;
                        }
                        params["meetingAppointList"] =
                            that.model.chooseList.map((item) => {
                                const splitItem = item.split(",");
                                return {
                                    salesmanId: splitItem[0],
                                    salesmanName: splitItem[1],
                                };
                            });
                    }
                    if (this.checkState0meetId) {
                        params.id = this.checkState0meetId;
                        updateMeet(params).then((res) => {
                            uni.$u.toast("提交成功");
                            uni.$u.route({
                                type: "reLaunch",
                                url: "pages_myMeeting/meeting/index",
                                // params: {
                                //     meetId: res.data,
                                // },
                            });
                        });
                    } else {
                        createMeet(params).then((res) => {
                            uni.$u.toast("提交成功");
                            uni.$u.route({
                                type: "reLaunch",
                                url: "pages_myMeeting/meeting/index",
                                // params: {
                                //     meetId: res.data,
                                // },
                            });
                        });
                    }
                })
                .finally(() => {
                    that.loading = false;
                });
        },
        formatAddress(str) {
            const reg = new RegExp(
                "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+?(区{1})|.+市|.+旗|.+海域|.+岛)?(?<village>.*)"
            );
            if (!str) return; // 中国4个直辖市
            const municipality = ["重庆", "北京", "上海", "天津"];
            const subStr = str.substring(0, 2);
            const isExist = municipality.includes(subStr);
            if (isExist) {
                str = str.substring(2, str.length - 1);
                str = `${subStr}省${str}`;
            }
            let addr = str.match(reg);
            if (!addr) return;
            const groups = Object.assign({}, addr.groups); // 如果是直辖市，截取地址后，把省字替换成市
            if (isExist) {
                groups.province = groups.province.replace("省", "市");
            }
            return {
                ...groups,
                isExist: isExist, // 是否为直辖市
            };
        },
        startTimeChange(e) {
            const time =
                typeof e.value === "number" ? e.value : Date.parse(e.value);
            this.model.startSubmitTime = moment(time).format(
                "YYYY-MM-DD HH:mm:ss"
            );
            this.pickerShow = false;
        },
        endTimeChange(e) {
            const time =
                typeof e.value === "number" ? e.value : Date.parse(e.value);
            this.model.endSubmitTime = moment(time).format(
                "YYYY-MM-DD HH:mm:ss"
            );
            this.pickerShow2 = false;
        },
        getLocation1() {
            console.log("333333 :>> ", this.meetingPersonList.length);
            uni.setStorageSync("meetingPersonList", this.meetingPersonList);
            this.$u.route({
                url: "/pages_initiateMeeting/initiateForm/person",
            });
        },
        getLocation() {
            const that = this;
            uni.chooseLocation({
                success: function (res) {
                    const addressGroups = that.formatAddress(res.address);
                    that.model.illegalPlace = res.address; //详细地址
                    // 经纬度
                    that.model.coordinatesX = res.longitude;
                    that.model.coordinatesY = res.latitude;
                    //省市区
                    that.model.city = addressGroups.isExist
                        ? ""
                        : addressGroups.city;
                    that.model.province = addressGroups.province;
                    that.model.county = addressGroups.county;
                    // 地址名
                    that.model.addressName = res.address + res.name;
                    that.model.illegalPlace = res.address + res.name; //详细地址
                },
                fail(locationResult) {
                    if (
                        locationResult.errMsg ===
                        "chooseLocation:fail auth deny"
                    ) {
                        uni.showModal({
                            title: "提示",
                            content: "填写违法地点需要获取您的定位权限",
                            success(modalResult) {
                                const { confirm } = modalResult;

                                if (confirm) {
                                    uni.openSetting({
                                        success(openSettingResult) {
                                            if (
                                                openSettingResult.authSetting[
                                                    "scope.userLocation"
                                                ] === true
                                            ) {
                                                that.getLocation();
                                            } else {
                                                uni.showToast({
                                                    title: "获取授权失败",
                                                    icon: "none",
                                                    duration: 2000,
                                                });
                                            }
                                        },
                                    });
                                }
                            },
                        });
                    }
                },
            });
        },
    },
};
</script>

<style>
page {
    background-color: #fff !important;
}
</style>

<style lang="scss" scoped>
.top {
    width: 100%;
    height: 108upx;
    padding: 0 30upx;
}
.form {
    padding: 0 38upx;
}
::v-deep.placeHolder {
    color: #666 !important;
    font-size: 28upx !important;
}
.radioGroupBox {
    display: flex;
    align-items: center;
}
.customClass {
    ::v-deep.u-form-item__body {
        flex-direction: column !important;
    }
    .chooseList {
        margin-top: 30upx;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        margin-right: 20rpx;
    }
}
.scopeList {
    width: 100%;
    height: 80upx;
    align-items: center;
    border-bottom: 1px solid #f3f3f3;
    .scopeLable {
        font-size: 28rpx;
        color: #666;
    }
    .activeColor {
        color: #588bf3;
    }
}
.scopeList:first-of-type {
    height: auto;
    padding-bottom: 20upx;
}
.scopeList:last-of-type {
    border-bottom: none;
}

.indexBox {
    width: 100vw;
    display: flex;
    flex-direction: column;
    &_confirmBox {
        width: 100%;
        height: 90rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 20rpx;
        box-sizing: border-box;
        border-bottom: 1px solid #f0e5e6;
    }
    &_indexList {
        width: 100%;
        height: calc(100% - 90rpx);
    }
}
.bottomFrom {
    padding-left: 40rpx;
    padding-right: 40rpx;
    padding-top: 20rpx;
    box-sizing: border-box;
    margin-top: 40rpx;
}
</style>
